import math
import sys
import torch
import torch.nn as nn
from core.submodule import *
import timm

class ResidualBlock(nn.Module):
    def __init__(self, in_planes, planes, norm_fn='group', stride=1):
        super(ResidualBlock, self).__init__()

        self.conv1 = nn.Conv2d(in_planes, planes, kernel_size=3, padding=1, stride=stride) # 输入in_planes通道，输出planes，尺寸/stride
        self.conv2 = nn.Conv2d(planes, planes, kernel_size=3, padding=1) # 通道不变，尺寸不变
        self.relu = nn.ReLU(inplace=True)

        num_groups = planes // 8 # 组数，每组8通道

        if norm_fn == 'group':
            self.norm1 = nn.GroupNorm(num_groups=num_groups, num_channels=planes) # 组归一化，分num_groups组，planes通道
            self.norm2 = nn.GroupNorm(num_groups=num_groups, num_channels=planes)
            if not (stride == 1 and in_planes == planes):
                self.norm3 = nn.GroupNorm(num_groups=num_groups, num_channels=planes)

        elif norm_fn == 'batch':
            self.norm1 = nn.BatchNorm2d(planes) # 批归一化，planes通道
            self.norm2 = nn.BatchNorm2d(planes)
            if not (stride == 1 and in_planes == planes):
                self.norm3 = nn.BatchNorm2d(planes)

        elif norm_fn == 'instance':
            self.norm1 = nn.InstanceNorm2d(planes) # 实例归一化，planes通道
            self.norm2 = nn.InstanceNorm2d(planes)
            if not (stride == 1 and in_planes == planes):
                self.norm3 = nn.InstanceNorm2d(planes)

        elif norm_fn == 'none':
            self.norm1 = nn.Sequential() # 空层
            self.norm2 = nn.Sequential()
            if not (stride == 1 and in_planes == planes):
                self.norm3 = nn.Sequential()

        if stride == 1 and in_planes == planes: # 输入输出通道相同且步长1的情况
            self.downsample = None # 不下采样
        else:
            self.downsample = nn.Sequential(
                nn.Conv2d(in_planes, planes, kernel_size=1, stride=stride), # 输入in_planes通道，输出planes通道，尺寸/stride
                self.norm3) # 对应的归一化

    def forward(self, x):
        y = x
        y = self.conv1(y) # 2d卷积，输入in_planes通道，输出planes，尺寸/stride
        y = self.norm1(y) # 归一化
        y = self.relu(y) # ReLU
        y = self.conv2(y) # 2d卷积，通道不变，尺寸不变
        y = self.norm2(y) # 归一化
        y = self.relu(y) # ReLU

        if self.downsample is not None: # 非输入输出通道相同且步长1的情况
            x = self.downsample(x) # 输入in_planes通道，输出planes通道，尺寸/stride，归一化

        return self.relu(x+y) # 残差连接

class BottleneckBlock(nn.Module):
    def __init__(self, in_planes, planes, norm_fn='group', stride=1):
        super(BottleneckBlock, self).__init__()

        self.conv1 = nn.Conv2d(in_planes, planes//4, kernel_size=1, padding=0)
        self.conv2 = nn.Conv2d(planes//4, planes//4, kernel_size=3, padding=1, stride=stride)
        self.conv3 = nn.Conv2d(planes//4, planes, kernel_size=1, padding=0)
        self.relu = nn.ReLU(inplace=True)

        num_groups = planes // 8

        if norm_fn == 'group':
            self.norm1 = nn.GroupNorm(num_groups=num_groups, num_channels=planes//4)
            self.norm2 = nn.GroupNorm(num_groups=num_groups, num_channels=planes//4)
            self.norm3 = nn.GroupNorm(num_groups=num_groups, num_channels=planes)
            if not stride == 1:
                self.norm4 = nn.GroupNorm(num_groups=num_groups, num_channels=planes)

        elif norm_fn == 'batch':
            self.norm1 = nn.BatchNorm2d(planes//4)
            self.norm2 = nn.BatchNorm2d(planes//4)
            self.norm3 = nn.BatchNorm2d(planes)
            if not stride == 1:
                self.norm4 = nn.BatchNorm2d(planes)

        elif norm_fn == 'instance':
            self.norm1 = nn.InstanceNorm2d(planes//4)
            self.norm2 = nn.InstanceNorm2d(planes//4)
            self.norm3 = nn.InstanceNorm2d(planes)
            if not stride == 1:
                self.norm4 = nn.InstanceNorm2d(planes)

        elif norm_fn == 'none':
            self.norm1 = nn.Sequential()
            self.norm2 = nn.Sequential()
            self.norm3 = nn.Sequential()
            if not stride == 1:
                self.norm4 = nn.Sequential()

        if stride == 1:
            self.downsample = None

        else:
            self.downsample = nn.Sequential(
                nn.Conv2d(in_planes, planes, kernel_size=1, stride=stride), self.norm4)

    def forward(self, x):
        y = x
        y = self.relu(self.norm1(self.conv1(y)))
        y = self.relu(self.norm2(self.conv2(y)))
        y = self.relu(self.norm3(self.conv3(y)))

        if self.downsample is not None:
            x = self.downsample(x)

        return self.relu(x+y)

class BasicEncoder(nn.Module):
    def __init__(self, output_dim=128, norm_fn='batch', dropout=0.0, downsample=3):
        super(BasicEncoder, self).__init__()
        self.norm_fn = norm_fn
        self.downsample = downsample

        if self.norm_fn == 'group':
            self.norm1 = nn.GroupNorm(num_groups=8, num_channels=64)

        elif self.norm_fn == 'batch':
            self.norm1 = nn.BatchNorm2d(64)

        elif self.norm_fn == 'instance':
            self.norm1 = nn.InstanceNorm2d(64)

        elif self.norm_fn == 'none':
            self.norm1 = nn.Sequential()

        self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=1 + (downsample > 2), padding=3)
        self.relu1 = nn.ReLU(inplace=True)

        self.in_planes = 64
        self.layer1 = self._make_layer(64,  stride=1)
        self.layer2 = self._make_layer(96, stride=1 + (downsample > 1))
        self.layer3 = self._make_layer(128, stride=1 + (downsample > 0))

        # output convolution
        self.conv2 = nn.Conv2d(128, output_dim, kernel_size=1)

        self.dropout = None
        if dropout > 0:
            self.dropout = nn.Dropout2d(p=dropout)

        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
            elif isinstance(m, (nn.BatchNorm2d, nn.InstanceNorm2d, nn.GroupNorm)):
                if m.weight is not None:
                    nn.init.constant_(m.weight, 1)
                if m.bias is not None:
                    nn.init.constant_(m.bias, 0)

    def _make_layer(self, dim, stride=1):
        layer1 = ResidualBlock(self.in_planes, dim, self.norm_fn, stride=stride)
        layer2 = ResidualBlock(dim, dim, self.norm_fn, stride=1)
        layers = (layer1, layer2)

        self.in_planes = dim
        return nn.Sequential(*layers)

    def forward(self, x, dual_inp=False):

        # if input is list, combine batch dimension
        is_list = isinstance(x, tuple) or isinstance(x, list)
        if is_list:
            batch_dim = x[0].shape[0]
            x = torch.cat(x, dim=0)
        x = self.conv1(x)
        x = self.norm1(x)
        x = self.relu1(x)
        x = self.layer1(x)
        x = self.layer2(x)
        x = self.layer3(x)
        x = self.conv2(x)

        if self.training and self.dropout is not None:
            x = self.dropout(x)

        if is_list:
            x = x.split(split_size=batch_dim, dim=0)

        return x

# 特征提取器的上下文网络，提取多尺度特征
class MultiBasicEncoder(nn.Module):
    def __init__(self, output_dim=[128], norm_fn='batch', dropout=0.0, downsample=3):
        super(MultiBasicEncoder, self).__init__()
        self.norm_fn = norm_fn # 控制归一化层的类型
        self.downsample = downsample # 下采样级别，到1/2^K尺寸

        # self.norm_111 = nn.BatchNorm2d(128, affine=False, track_running_stats=False)
        # self.norm_222 = nn.BatchNorm2d(128, affine=False, track_running_stats=False)

        if self.norm_fn == 'group':
            self.norm1 = nn.GroupNorm(num_groups=8, num_channels=64) # 组归一化，分8组，64通道

        elif self.norm_fn == 'batch':
            self.norm1 = nn.BatchNorm2d(64) # 批归一化，64通道

        elif self.norm_fn == 'instance':
            self.norm1 = nn.InstanceNorm2d(64) # 实例归一化，64通道

        elif self.norm_fn == 'none':
            self.norm1 = nn.Sequential() # 空层

        self.conv1 = nn.Conv2d(3, 64, kernel_size=7, stride=1 + (downsample > 2), padding=3) # 输入3通道，输出64通道，若downsample>2，尺寸/2，否则尺寸不变
        self.relu1 = nn.ReLU(inplace=True)

        self.in_planes = 64
        self.layer1 = self._make_layer(64, stride=1) # 创建层结构，输入64通道，输出64通道，尺寸不变
        self.layer2 = self._make_layer(96, stride=1 + (downsample > 1)) # 创建层结构，输入64通道，输出96通道，若downsample>1，尺寸/2，否则尺寸不变
        self.layer3 = self._make_layer(128, stride=1 + (downsample > 0)) # 创建层结构，输入96通道，输出128通道，若downsample>0，尺寸/2，否则尺寸不变
        self.layer4 = self._make_layer(128, stride=2) # 创建层结构，输入128通道，输出128通道，尺寸/2
        self.layer5 = self._make_layer(128, stride=2) # 创建层结构，输入128通道，输出128通道，尺寸/2

        output_list = [] # 存储以output_dim每个list元素的第2个元素值为输出通道的顺序块
        for dim in output_dim: # output_dim=[[128,128,128],[128,128,128]]
            conv_out = nn.Sequential(
                ResidualBlock(128, 128, self.norm_fn, stride=1), # 输入128通道，输出128通道，尺寸不变，残差连接
                nn.Conv2d(128, dim[2], 3, padding=1)) # 输入128通道，输出dim[2](128)通道，尺寸不变
            output_list.append(conv_out)
        self.outputs04 = nn.ModuleList(output_list) # 合并所有conv_out为一个块

        output_list = []
        for dim in output_dim:
            conv_out = nn.Sequential(
                ResidualBlock(128, 128, self.norm_fn, stride=1), # 输入128通道，输出128通道，尺寸不变，残差连接
                nn.Conv2d(128, dim[1], 3, padding=1)) # 输入128通道，输出dim[1](128)通道，尺寸不变
            output_list.append(conv_out)
        self.outputs08 = nn.ModuleList(output_list)

        output_list = []
        for dim in output_dim:
            conv_out = nn.Conv2d(128, dim[0], 3, padding=1) # 输入128通道，输出dim[0](128)通道，尺寸不变
            output_list.append(conv_out)
        self.outputs16 = nn.ModuleList(output_list)

        if dropout > 0: # Dropout正则化的概率
            self.dropout = nn.Dropout2d(p=dropout) # Dropout正则化，dropout概率对每个通道置零，减少过拟合现象
        else: # 默认不进行Dropout正则化
            self.dropout = None

        # 初始化上下文网络的权重和偏置
        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                nn.init.kaiming_normal_(m.weight, mode='fan_out', nonlinearity='relu')
            elif isinstance(m, (nn.BatchNorm2d, nn.InstanceNorm2d, nn.GroupNorm)):
                if m.weight is not None:
                    nn.init.constant_(m.weight, 1)
                if m.bias is not None:
                    nn.init.constant_(m.bias, 0)

    # 创建层结构
    def _make_layer(self, dim, stride=1):
        layer1 = ResidualBlock(self.in_planes, dim, self.norm_fn, stride=stride) # 使用norm_fn归一化，输入in_planes通道，输出dim通道，尺寸/stride，残差连接原始张量和处理后张量
        layer2 = ResidualBlock(dim, dim, self.norm_fn, stride=1) # 使用norm_fn归一化，通道不变，尺寸不变，残差连接原始张量和处理后张量
        layers = (layer1, layer2) # 将layer1和layer2合为元组

        self.in_planes = dim # 用于下一个层结构的输入通道
        return nn.Sequential(*layers) # 将layers解包为layer1和layer2，合为一个顺序层

    def forward(self, x, dual_inp=False, num_layers=3): # 输入3通道，原尺寸

        x = self.conv1(x) # 输入3通道，输出64通道，若downsample>2，尺寸/2，否则尺寸不变；默认downsample=2，尺寸不变
        x = self.norm1(x) # 批归一化
        x = self.relu1(x) # ReLU
        x = self.layer1(x) # 输入64通道，输出64通道，尺寸不变
        x = self.layer2(x) # 输入64通道，输出96通道，若downsample>1，尺寸/2，否则尺寸不变；默认downsample=2，1/2原尺寸
        x = self.layer3(x) # 输入96通道，输出128通道，若downsample>0，尺寸/2，否则尺寸不变；默认downsample=2，1/4原尺寸
        if dual_inp: # 双输入，输出带有处理后的x；默认downsample=2，1/4原尺寸
            v = x
            x = x[:(x.shape[0]//2)] # 取batch_size//2的image1张量

        outputs04 = [f(x) for f in self.outputs04] # 对ModuleList的每个层输入x做前向传播，输出List(2个元素)，output_dim的List元素的第2个元素为通道数

        if num_layers == 1: # GRU的层数为1
            return (outputs04, v) if dual_inp else (outputs04) # 输出多尺度上下文特征，若双输出，输出元组(List,x)，否则输出元组(List)，128通道；默认downsample=2，(1/4原尺寸)

        y = self.layer4(x) # 输入128通道，输出128通道；默认downsample=2，1/8原尺寸
        outputs08 = [f(y) for f in self.outputs08] # 对ModuleList的每个层输入x做前向传播，输出List(2个元素)，output_dim的List元素的第1个元素为通道数

        if num_layers == 2: # GRU的层数为1
            return (outputs04, outputs08, v) if dual_inp else (outputs04, outputs08) # 输出多尺度上下文特征，若双输出，输出元组(List,List,x)，否则输出元组(List,List)，128通道；默认downsample=2，(1/4原尺寸,1/8原尺寸)

        z = self.layer5(y) # 输入128通道，输出128通道；默认downsample=2，1/16原尺寸
        outputs16 = [f(z) for f in self.outputs16] # 对ModuleList的每个层输入x做前向传播，输出List(2个元素)，output_dim的List元素的第0个元素为通道数

        return (outputs04, outputs08, outputs16, v) if dual_inp else (outputs04, outputs08, outputs16) # 输出多尺度上下文特征，若双输出，输出元组(List,List,List,x)，否则输出元组(List,List,List)，128通道；默认downsample=2，(1/4原尺寸,1/8原尺寸,1/16原尺寸)

class SubModule(nn.Module):
    def __init__(self):
        super(SubModule, self).__init__()

    def weight_init(self):
        for m in self.modules():
            if isinstance(m, nn.Conv2d):
                n = m.kernel_size[0] * m.kernel_size[1] * m.out_channels
                m.weight.data.normal_(0, math.sqrt(2. / n))
            elif isinstance(m, nn.Conv3d):
                n = m.kernel_size[0] * m.kernel_size[1] * m.kernel_size[2] * m.out_channels
                m.weight.data.normal_(0, math.sqrt(2. / n))
            elif isinstance(m, nn.BatchNorm2d):
                m.weight.data.fill_(1)
                m.bias.data.zero_()
            elif isinstance(m, nn.BatchNorm3d):
                m.weight.data.fill_(1)
                m.bias.data.zero_()

# 特征提取器的特征网络，提取多尺度特征
class Feature(SubModule):
    def __init__(self):
        super(Feature, self).__init__()
        pretrained =  True
        model = timm.create_model('mobilenetv2_100', pretrained=pretrained, features_only=True) # timm库的mobilenetv2网络，使用ImageNet预训练权重，保留特征提取部分
        layers = [1,2,3,5,6]
        chans = [16, 24, 32, 96, 160]

        # mobilenetv2的特征提取部分(前3层)
        self.conv_stem = model.conv_stem # 卷积层conv_stem
        self.bn1 = model.bn1 # 批归一化层bn1
        self.act1 = model.act1 # ReLU激活函数层act1

        # mobilenetv2的blocks块部分(第0~5层)
        self.block0 = torch.nn.Sequential(*model.blocks[0:layers[0]]) # 解包blocks块，取块内的第0层
        self.block1 = torch.nn.Sequential(*model.blocks[layers[0]:layers[1]]) # 取第1层
        self.block2 = torch.nn.Sequential(*model.blocks[layers[1]:layers[2]]) # 取第2层
        self.block3 = torch.nn.Sequential(*model.blocks[layers[2]:layers[3]]) # 取第3、4层
        self.block4 = torch.nn.Sequential(*model.blocks[layers[3]:layers[4]]) # 取第5层

        # 残差块，拼接张量，带有实例归一化
        self.deconv32_16 = Conv2x_IN(chans[4], chans[3], deconv=True, concat=True) # 对x：输入160通道，输出96通道，2d转置尺寸*2；拼接张量x,rem
        self.deconv16_8 = Conv2x_IN(chans[3]*2, chans[2], deconv=True, concat=True) # 对x：输入96*2通道，输出32通道，2d转置尺寸*2；拼接张量x,rem
        self.deconv8_4 = Conv2x_IN(chans[2]*2, chans[1], deconv=True, concat=True) # 对x：输入32*2通道，输出24通道，2d转置尺寸*2；拼接张量x,rem

        # 基本卷积块，带有实例归一化
        self.conv4 = BasicConv_IN(chans[1]*2, chans[1]*2, kernel_size=3, stride=1, padding=1) # 2d卷积，输入24*2通道，输出24*2通道，尺寸不变，实例归一化，LeakyReLU

    def forward(self, x):
        x = self.act1(self.bn1(self.conv_stem(x))) # 输入3通道，输出32通道，卷积核3*3，步长1，1/2原尺寸
        x2 = self.block0(x) # 输入32通道，输出16通道，尺寸不变
        x4 = self.block1(x2) # 输入16通道，输出24通道，1/4原尺寸
        x8 = self.block2(x4) # 输入24通道，输出32通道，1/8原尺寸
        x16 = self.block3(x8) # 输入32通道，输出96通道，1/16原尺寸
        x32 = self.block4(x16) # 输入96通道，输出160通道，1/32原尺寸

        x16 = self.deconv32_16(x32, x16) # 对x32：输入160通道，输出96通道，1/16原尺寸；拼接张量x32,x16，输出96*2通道，1/16原尺寸
        x8 = self.deconv16_8(x16, x8) # 对x16：输入96*2通道，输出32通道，1/8原尺寸；拼接张量x16,x8，输出32*2通道，1/8原尺寸
        x4 = self.deconv8_4(x8, x4) # 对x8：输入32*2通道，输出24通道，1/4原尺寸；拼接张量x8,x4，输出24*2通道，1/4原尺寸
        x4 = self.conv4(x4) # 2d卷积，输入24*2通道，输出24*2通道，1/4原尺寸

        return [x4, x8, x16, x32] # 返回多尺度特征
